package algorithm.sort.review2;

import java.util.Arrays;

public class Merge {
    public static void main(String[] args) {
        int[] arr = {3, 3, 4, 1, 3, 56, 242, 1};
        int[] tmp = new int[arr.length];
        sortReview(arr, 0, arr.length - 1, tmp);

        System.out.println(Arrays.toString(arr));
    }

    public static void sort(int[] arr, int left, int right, int[] tmp) {
        if (left < right) {
            int mid = (left + right) / 2;
            //递归分左边
            sort(arr, left, mid, tmp);
            //递归分右边
            sort(arr, mid + 1, right, tmp);
            //合并
            merge(arr, left, mid, right, tmp);
        }
    }

    public static void merge(int[] dataArr, int left, int mid, int right, int[] tmpArr) {
        int l = left;
        int r = mid + 1;
        int k = 0;
        while (l <= mid && r <= right) {
            if (dataArr[l] < dataArr[r]) {
                tmpArr[k++] = dataArr[l++];
            } else {
                tmpArr[k++] = dataArr[r++];
            }
        }
        if (r <= right) {
            while (r <= right) {
                tmpArr[k++] = dataArr[r++];
            }
        } else {
            while (l <= mid) {
                tmpArr[k++] = dataArr[l++];
            }
        }
        k = 0;
        for (int i = left; i <= right; i++) {
            dataArr[i] = tmpArr[k++];
        }
    }

    public static void sortReview(int[] arr, int left, int right, int[] tmp) {
        if (left < right) {
            //分
            int mid = (left + right) / 2;
            sortReview(arr, left, mid, tmp);
            sortReview(arr, mid + 1, right, tmp);
            mergeReview(arr, left, mid, right, tmp);
        }
    }

    /**
     * mergeReview
     *
     * @param arr
     * @param left
     * @param mid
     * @param right
     * @param tmp
     */
    public static void mergeReview(int[] arr, int left, int mid, int right, int[] tmp) {
        int l = left;
        int r = mid + 1;
        int k = 0;
        while (l <= mid && r <= right) {
            if (arr[l] < arr[r]) {
                tmp[k++] = arr[l++];
            } else {
                tmp[k++] = arr[r++];
            }
            while (l <= mid) {
                tmp[k++] = arr[l++];
            }
            while (r <= right) {
                tmp[k++] = arr[r++];
            }
        }
        k = 0;
        for (int i = left; i <= right; i++) {
            arr[i] = tmp[k++];
        }
    }
}
